package host.haiwai.service.impl;

import host.haiwai.entity.Menu;
import host.haiwai.mapper.MenuMapper;
import host.haiwai.service.MenuServer;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author joefche / JC
 * @since 2021-08-29
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuServer {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> listWithTree() {
        // 1.查询出所有的分类
        List<Menu> entities = menuMapper.selectList(null);
        //List<Menu> entities = menuMapper.selectList(null);

        // 2.组装成父子的树形结构

        List<Menu> level1Menus = new ArrayList<>();
        // 找到所有的一级分类
        for (Menu entity : entities) {
            if (entity.getParentId() == 0) {
                level1Menus.add(entity);
            }
        }
        //递归查找下级分类
        for (Menu level1Menu : level1Menus) {
            level1Menu.setChildren(getChildrens(level1Menu, entities));
        }
        //排序
        level1Menus.sort(new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                return (o1.getMenuSort() == null ? 0 : o1.getMenuSort()) - (o2.getMenuSort() == null ? 0 : o2.getMenuSort());
            }
        });
        return level1Menus;
    }

    /**
     * 递归查找所有的下级分类
     * 在这一级别的分类中找下级分类
     *
     * @param root 当前级别的分类
     * @param all  全部分类
     * @return 下一级分类
     */
    private List<Menu> getChildrens(Menu root, List<Menu> all) {
        List<Menu> children = new ArrayList<>();
        for (Menu a : all) {
            if (a.getParentId().equals(root.getMenuId())) {
                a.setChildren(getChildrens(a, all));
                children.add(a);
            }
        }
        children.sort(new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                return (o1.getMenuSort() == null ? 0 : o1.getMenuSort()) - (o2.getMenuSort() == null ? 0 : o2.getMenuSort());
            }
        });
        return children;
    }
}
